package zj.it.bhne.gridengineeringsurvey.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.dialog.widget.NormalDialog;

import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.activity.AboutActivity;
import zj.it.bhne.gridengineeringsurvey.activity.AccountActivity;
import zj.it.bhne.gridengineeringsurvey.activity.LoginActivity;
import zj.it.bhne.gridengineeringsurvey.activity.UserImformationActivity;
import zj.it.bhne.gridengineeringsurvey.entity.VersionBean;
import zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager;
import zj.it.bhne.gridengineeringsurvey.myutils.XCRoundRectImageView;
import zj.it.bhne.gridengineeringsurvey.myutils.config.NetConfig;

import static zj.it.bhne.gridengineeringsurvey.myutils.GetVersion.update;
import static zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager.getThreadPool;

/**
 * 项目首页中BottomActivity的第三个页面
 */
public class ThreeFragment extends Fragment implements View.OnClickListener {

    LogInDiaLog mDiaLog;
    private TextView three_tv_name;


   /* @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();//先清除已经建好的menu
        MenuInflater inflater = requireNonNull(getActivity()).getMenuInflater();
        //根据各种条件，重新设置menu
        inflater.inflate(R.menu.add_action, menu);
        menu.close();
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setVisible(false);
        }
        super.onPrepareOptionsMenu(menu);
    }*/
    private LinearLayout three_btn_back;
    private ProgressDialog mProgressDialog;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //若工作完成，取消动画，初始化界面
            mProgressDialog.cancel();
        }
    };
    /**
     * 线程
     */
    private Runnable mRunnable = () -> {
        //需要耗时的工作
        appUpdate();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_three, container, false);
        initView(view);
        return view;
    }

    /**
     * 布局
     */
    private void initView(View view) {
        three_tv_name = view.findViewById(R.id.three_tv_name);
        XCRoundRectImageView header_img = view.findViewById(R.id.ft_header_iv);
        header_img.setOnClickListener(this);

        RelativeLayout three_btn_more = view.findViewById(R.id.three_btn_more);
        RelativeLayout three_btn_above = view.findViewById(R.id.three_btn_above);
        RelativeLayout three_btn_inter = view.findViewById(R.id.three_btn_inter);
        three_btn_inter.setOnClickListener(this);
        three_tv_name.setOnClickListener(this);
        three_btn_more.setOnClickListener(this);
        three_btn_above.setOnClickListener(this);
        three_btn_back = view.findViewById(R.id.three_btn_back);
        three_btn_back.setOnClickListener(this);
        /*RelativeLayout three_btn_inter = view.findViewById(R.id.three_btn_inter);
        three_btn_inter.setOnClickListener(this);*/
        ImageButton activity_ib_back = view.findViewById(R.id.activity_ib_back);
        activity_ib_back.setOnClickListener(this);
        TextView activity_tv_title = view.findViewById(R.id.activity_tv_title);
        activity_tv_title.setOnClickListener(this);
        TextView activity_tv_save = view.findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);

        activity_ib_back.setVisibility(View.GONE);
        activity_tv_title.setText(getString(R.string.bottom_three));
        activity_tv_save.setVisibility(View.GONE);
        RelativeLayout three_btn_exit = view.findViewById(R.id.three_btn_exit);
        three_btn_exit.setOnClickListener(this);
        RelativeLayout three_rl_account = view.findViewById(R.id.three_rl_account);
        three_rl_account.setOnClickListener(this);
        isLogin();
    }

    /**
     * 判断是否登录
     */
    public void isLogin() {
        if (MyApplication.getInstances().IsLogin()) {
            three_btn_back.setVisibility(View.VISIBLE);
            String names = SPUtils.getInstance().getString("name");
            if (!names.equals("")) {
                three_tv_name.setText(names);
            }
        } else {
            three_btn_back.setVisibility(View.GONE);
        }
    }

    /**
     * 版本更新
     */
    private void appUpdate() {
        SPUtils.getInstance().put("update", "1");
        String version = HttpConfig.getVersion();
        ////Log.e("TAG", "appUpdate: " + version);
        if (version != null) {
            VersionBean versionBean = HttpConfig.parseXMLVersion(version);
            if (versionBean.isUpdate()) {
                update(versionBean.getUpdateUrl(), getActivity());
            } else {
                ToastUtils.showShort("当前为最新版本");
            }
        } else {
            ToastUtils.showShort("网络错误");
        }

    }

    /**
     * 按钮的点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.three_tv_name:
                if (MyApplication.getInstances().IsLogin()) {
                    MyUtils.getToast(getContext(), "已处于在线状态");
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();
                }
                break;
            case R.id.three_btn_more:
                showSetNetHttpDialog();
                break;
            case R.id.three_btn_above:
                startActivity(new Intent(getContext(), AboutActivity.class));
                break;
            case R.id.three_btn_back:
                backDialog();
                break;
            case R.id.three_btn_inter:
                //chinaEnglish();
                /*
                 *版本更新
                 */

                if (NetworkUtils.isConnected()) {
                    mProgressDialog = new ProgressDialog(getContext());
                    mProgressDialog.setMessage("正在检查更新,请稍等...");
                    mProgressDialog.setCanceledOnTouchOutside(false);
                    mProgressDialog.show();
                    ThreadManager.ThreadPool threadPool = getThreadPool();
                    threadPool.execute(mRunnable);
                } else {
                    ToastUtils.showShort("网络无连接");
                }

                break;
            case R.id.three_btn_exit:
                final NormalDialog dialog = new NormalDialog(getContext());
                dialog.content("是否要退出程序?")//
                        .style(NormalDialog.STYLE_TWO)//
                        .btnNum(2)
                        .title("退出")
                        .btnText("取消", "退出")//
                        .show();
                dialog.setOnBtnClickL(
                        dialog::dismiss, () -> {
                            dialog.dismiss();
                            /*Objects.requireNonNull(getActivity()).finish();
                            System.exit(0);*/
                            SPUtils.getInstance().put("update", "0");
                            MyApplication.getInstances().exit();
                        });
                //System.exit(0);
                break;
            case R.id.three_rl_account:
                startActivity(new Intent(getContext(), AccountActivity.class));
                break;
            case R.id.ft_header_iv:
                startActivity(new Intent(getActivity(), UserImformationActivity.class));
                break;
        }
    }

    /**
     * 设置网络
     */
    private void showSetNetHttpDialog() {
        View viewDialog = View.inflate(getContext(), R.layout.dialog_set_netip, null);
        viewDialog.measure(0, 0);
        int measuredHeight = viewDialog.getMeasuredHeight();
        int measuredWidth = viewDialog.getMeasuredWidth();
        mDiaLog = new LogInDiaLog(getContext(), measuredWidth, measuredHeight, viewDialog, R.style.dialog);
        EditText IPSet = mDiaLog.findViewById(R.id.IPSet);
        EditText HTTPSet = mDiaLog.findViewById(R.id.HTTPSet);
        Button setNetConfirm = mDiaLog.findViewById(R.id.SetNet_bt_confirm);
        Button setNetCancel = mDiaLog.findViewById(R.id.SetNet_bt_cancel);
        String iptext = SPUtils.getInstance().getString("IPTEXT");
        String httptext = SPUtils.getInstance().getString("HTTPTEXT");
        IPSet.setText(iptext);
        HTTPSet.setText(httptext);
        setNetConfirm.setOnClickListener(v -> {
            String IPSetString = IPSet.getText().toString().trim();
            String HTTPSetString = HTTPSet.getText().toString().trim();
            if (!TextUtils.isEmpty(IPSetString) || !TextUtils.isEmpty(HTTPSetString)) {
                SPUtils.getInstance().put("IPTEXT", IPSetString);
                SPUtils.getInstance().put("HTTPTEXT", HTTPSetString);
                //http://192.168.32.98:8080/
                NetConfig.MAIN = "http://" + IPSetString + ":" + HTTPSetString;
                mDiaLog.dismiss();
            } else {
                ToastUtils.showShort("请填写完整");
            }
        });
        setNetCancel.setOnClickListener(v -> mDiaLog.dismiss());
        mDiaLog.show();
    }

    /*
     * 中英切换
     */
    /*private void chinaEnglish() {
        //获取当前语言。
        String ss = Locale.getDefault().getLanguage();
        Intent intent = new Intent();
        intent.putExtra("item_id", 3);
        //如果当前为中文就变成英文，反之变成中文
        if (ss.equals("zh")) {
            Locale.setDefault(Locale.ENGLISH);
            Configuration configuration = Objects.requireNonNull(getActivity()).getBaseContext().getResources().getConfiguration();
            configuration.locale = Locale.ENGLISH;
            getActivity().getBaseContext().getResources().updateConfiguration(configuration, getActivity().getBaseContext().getResources().getDisplayMetrics());
            getActivity().setIntent(intent);
            getActivity().recreate();
        } else {
            Locale.setDefault(Locale.CHINESE);
            Configuration configuration = Objects.requireNonNull(getActivity()).getBaseContext().getResources().getConfiguration();
            configuration.locale = Locale.CHINESE;
            getActivity().getBaseContext().getResources().updateConfiguration(configuration, getActivity().getBaseContext().getResources().getDisplayMetrics());
            getActivity().setIntent(intent);
            getActivity().recreate();
        }
    }*/

    /**
     * 退出登录
     */
    private void backDialog() {
        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content("是否要退出登录?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("退出")
                .btnText("取消", "退出")//
                .show();
        dialog.setOnBtnClickL(
                dialog::dismiss, () -> {
                    dialog.dismiss();
                    getActivity().finish();
                    SPUtils.getInstance().put("islogin", "0");
                    SPUtils.getInstance().put("mUsername", "");
                    SPUtils.getInstance().put("mPassword", "");
                    SPUtils.getInstance().put("token", "");
                    SPUtils.getInstance().put("name", "");
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                });

    }


    @SuppressLint("CommitTransaction")
    @Override
    public void onDestroy() {
        super.onDestroy();
        ThreeFragment fragment = new ThreeFragment();
        FragmentManager manager = getFragmentManager();
        assert manager != null;
        @SuppressLint("CommitTransaction") FragmentTransaction transaction = manager.beginTransaction();
        manager.beginTransaction().remove(fragment);
        transaction.hide(fragment);
    }

}
